import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report, accuracy_score

# 1. 数据准备
# 确保文件路径正确
try:
    df = pd.read_json(r'D:\网络爬虫\douban\movies.json')  # 假设数据文件为 movies.json
    print(df.head())  # 输出数据的前几行
    print(df.columns)  # 输出所有列名
except FileNotFoundError:
    print("文件未找到，请检查文件路径。")
    exit()

# 2. 数据预处理
# 根据实际列名进行修改
X = df['title']  # 假设电影标题在 title 列
y = df['rating']  # 假设评分在 rating 列

# 使用 TF-IDF 向量化
vectorizer = TfidfVectorizer()
X_vectorized = vectorizer.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_vectorized, y, test_size=0.2, random_state=42)

# 3. 模型训练
# 创建 SVM 模型
model = SVC(kernel='linear')

# 训练模型
model.fit(X_train, y_train)

# 4. 模型评估
# 预测测试集
y_pred = model.predict(X_test)

# 输出评估结果
print("准确率:", accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred))
